﻿using System;
using System.Collections.Generic;
using System.Data;

namespace Jasmine.Extensions.Tables
{
    public static class TableExtension
    {
        /// <summary>
        /// Creates a list of objects of type T by mapping the rows of the specified DataTable to instances of T.
        /// </summary>
        /// <remarks>Only properties in T that match the column names in the DataTable and are public and
        /// settable will be populated. Column values of DBNull are ignored and the corresponding properties are left at
        /// their default values. The method requires that T has a public parameterless constructor.</remarks>
        /// <typeparam name="T">The type of objects to create for each row in the DataTable. Must have a public parameterless constructor
        /// and public settable properties matching the column names.</typeparam>
        /// <param name="table">The DataTable whose rows will be converted to objects of type T. Each column name should correspond to a
        /// property name in T.</param>
        /// <returns>A list of objects of type T, each representing a row from the DataTable. The list will be empty if the
        /// DataTable contains no rows.</returns>
        public static List<T> ToList<T>(this DataTable table)
        {
            var list = new List<T>();
            foreach (DataRow row in table.Rows)
            {
                T item = (T)Activator.CreateInstance(typeof(T));
                foreach (DataColumn column in table.Columns)
                {
                    var property = typeof(T).GetProperty(column.ColumnName);
                    if (property != null && row[column] != DBNull.Value)
                    {
                        property.SetValue(item, Convert.ChangeType(row[column], property.PropertyType), null);
                    }
                }
                list.Add(item);
            }
            return list;
        }

    }
}
